from odoo import fields, models, api

CHANGE_TYPE = [('add', '+'), ('subtract', '-')]
RECORD_SELECTION = [ ('rp.ship.order', '订单')]


class RpFlowLog(models.Model):
    _name = 'rp.flow.log'
    _description = '流水记录'
    _rec_name = 'code'

    code = fields.Char(string='序列号', default='RP_FLO/****', copy=False, index=True)
    operation_person = fields.Many2one(string='操作人', comodel_name='res.users', copy=False)
    rp_customer_id = fields.Many2one(string='客户', comodel_name='rp.customer', copy=False)
    category_id = fields.Many2one(string='一级分类', comodel_name='rp.flow.record.category', copy=False)
    related_record = fields.Reference(string='关联记录', selection=RECORD_SELECTION, copy=False, index=True)

    change_type = fields.Selection(string='变化类型', selection=CHANGE_TYPE, index=True, copy=False)
    funds_change = fields.Float(string='价格变动', copy=False, index=True)
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)
    remark = fields.Char(string='备注', copy=False)
    rp_flow_record_log_line_ids = fields.One2many(string='流水详情', comodel_name='rp.flow.record.log.line', inverse_name='rp_flow_record_id', copy=False)
    date_create = fields.Datetime(string='创建时间', default=fields.datetime.now(), copy=False, index=True)

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.flow.log') or '/'
        return super(RpFlowLog, self).create(vals_list)


class RpFlowRecordLogLine(models.Model):
    _name = 'rp.flow.record.log.line'
    _description = '流水详情'

    rp_flow_record_id = fields.Many2one(string='关联主表', comodel_name='rp.flow.log', copy=False)
    flow_record_category_id = fields.Many2one(string='类型', comodel_name='rp.flow.record.category', copy=False)

    change_type = fields.Selection(string='变化类型', selection=CHANGE_TYPE, index=True, copy=False)
    funds_change = fields.Float(string='价格变动', copy=False, index=True)
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)
    desc = fields.Char(string='描述', copy=False)
